package com.qianji.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 钟丽诗
 * @Date 2021.4.27
 * Jwt工具类，用于生成Token及验证Token
 */
@Component
public class JwtUtils {

    //设置过期时间为30天
    private static long EXP =/*30 * 24 * */30 * 60 * 1000;//30分

    /*
    * 公钥
    * MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAobQlTp4X+Vv3eRTVcICyVGNBd+65KHoVVCgsD1KMGO6SQk6EP0RRiq1zrJLswCWNWUi3QEQcLBf+3RsJCYOreNX92x9Jyzy5LnmU5SA1n4BilhFOVuFfJhgWiLCmj5PTR8d2a35W1VgjSrwGuyC3TZH3BsUgL/jjGO7cNtWJ2Lmez2x2HiaYHFCBfxqojubpx5Drya5Ab84x8HFJtOSxuyJ4Z4o9VtlvwHjpvyvp4TIu1vC8x8ZHjT+s3jYixIkBBwDkY6oBO6YGik8eieif1vehBUF3ysezEZHZ8+72kPyiabUu/6HMVftHsfGKIRbXj2obnGHxN7LMMAo08g137QIDAQAB
    * */

    //jwt秘钥
    private static String JWT_SECERT = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQChtCVOnhf5W/d5FNVwgLJUY0F37rkoehVUKCwPUowY7pJCToQ/RFGKrXOskuzAJY1ZSLdARBwsF/7dGwkJg6t41f3bH0nLPLkueZTlIDWfgGKWEU5W4V8mGBaIsKaPk9NHx3ZrflbVWCNKvAa7ILdNkfcGxSAv+O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Y7q4X9dTOa/eBajlH4ncOfE5ENyoQFli4h3GmUvnIbAIihjev77+2QBvRaTFfD/kWuN0pjr8+HbBpdeu307a+Fewu4EM/4YYXsYR+fhrnuVqSTDsM7vr6HmO0nsgjPoBUAGLI0zopZ0GPSKbfOq8e+wKBgDe9CTkNtu4D45lTnA2OK0KMPumRnQOrpupyLTFfgI5fa/HfX6C6LVFHaYAqhCKGdxeJHSE+asPw30AJQUwPw+Ew/Il5KOLXHDNmtLYmTNlYk9OIOmfbV6BcHqGt+19syZbVb7Qf3GGUIg2kR9WrNyOtYSmZiPP/2R1zjEjoQgmt";

    /**
     *签发JWT
     *
     * @param name key
     * @param password 可以是json数据（如：用户名和密码）
     * @return
     */
    public static String createJwtToken(String name, String password){
        String token = "";
        try {
            //过期时间
            Date exp = new Date(System.currentTimeMillis()+EXP);

            //私钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(JWT_SECERT);

            //设置头消息
            Map<String,Object> header = new HashMap<>();
            header.put("typ","JWT");
            header.put("alg","HS256");

            token = JWT.create()
                    .withHeader(header)
                    .withClaim("userName",name)
                    .withClaim("password",password)
                    .withExpiresAt(exp)//设置过期时间
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return token;
    }

    public static Map<String,Object> checkJwtToken(String token){
        Map<String,Object> messageMap = new HashMap<>();
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_SECERT);

            JWTVerifier jwtVerifier = JWT.require(algorithm).build();

            DecodedJWT decodedJWT = jwtVerifier.verify(token);

            String userName = decodedJWT.getClaim("userName").asString();

            String password = decodedJWT.getClaim("password").asString();

            if(new Date().getTime() > decodedJWT.getExpiresAt().getTime()){
                return null;
            }

            messageMap.put("userName",userName);
            messageMap.put("password",password);


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        return messageMap;
    }


}
